package zisu.netty.practice.netty.my;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.ScheduledFuture;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @Desc: ""
 * @Author: caixiang
 * @DATE: 2020/8/4 9:38
 */
public class MyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private int count = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] buffer = new byte[msg.readableBytes()];
        msg.readBytes(buffer);
        String res = new String(buffer, StandardCharsets.UTF_8);
        System.out.println("客户端接收到消息："+res);
        System.out.println("客户端接收到的消息数量"+ (++count));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println("进入异常 ："+cause.getMessage());
        cause.printStackTrace();
        ctx.close();

//        NettyClient.INSTANCE.setConnectionStatus(false);
//        boolean reconnect = NettyClient.INSTANCE.reconnect();
//        if(!reconnect){
//            System.err.println("耗尽最大重连次数");
//        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        //使用客户端发送10条数据 hello，server 带编号。
        for(int i=0;i<10;i++){
            ByteBuf buf = Unpooled.copiedBuffer("hello,server" + i+" ", StandardCharsets.UTF_8);
            ctx.writeAndFlush(buf);
        }
    }



}
